package com.cyzy.educationalai.sercive;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Flux;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zxw
 * @create 2025-05-29 下午7:00
 */
@Service
public class DeepSeekService {

    private final WebClient webClient;

    public DeepSeekService(
            @Value("${spring.ai.openai.base-url}") String baseUrl,
            @Value("${spring.ai.openai.api-key}") String apiKey) {
        this.webClient = WebClient.builder()
                .baseUrl(baseUrl)
                .defaultHeader(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                .build();
    }

    public Flux<String> chat(String prompt, String chatId) {
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-chat");

        List<Object> list = new ArrayList<>();
        Map<String, Object> mp = new HashMap<>();
        mp.put("role", "user");
        mp.put("content", prompt);

        list.add(mp);
        requestBody.put("messages", list);
        requestBody.put("stream", "true");

//        Map<String, Object> requestBody = Map.of(
//                "model", "deepseek-chat",
//                "messages", List.of(
//                        Map.of("role", "user", "content", prompt)
//                ),
//                "stream", true
//        );

        return webClient.post()
                .uri("/chat/completions")
                .bodyValue(requestBody)
                .retrieve()
                .bodyToFlux(String.class);
    }
}
